use ggez::{input::keyboard::KeyCode, Context};
use hecs::World;
use crate::components::*;

pub struct MainMenuState {
    pub selected: usize,
    pub total: usize,
}

impl Default for MainMenuState {
    fn default() -> Self {
        Self { selected: 0, total: 1 } 
    }
}

pub fn run_menu_system(world: &mut World, context: &mut Context, menu_state: &mut MainMenuState) {
    // 上下键选择菜单项
    if context.keyboard.is_key_just_pressed(KeyCode::Up) {
        if menu_state.selected == 0 {
            menu_state.selected = menu_state.total - 1;
        } else {
            menu_state.selected -= 1;
        }
    }
    if context.keyboard.is_key_just_pressed(KeyCode::Down) {
        menu_state.selected = (menu_state.selected + 1) % menu_state.total;
    }
    
    // 回车确认选择
    if context.keyboard.is_key_just_pressed(KeyCode::Return) {
        {
            let mut query = world.query::<&mut Gameplay>();
            let gameplay = query.iter().next().unwrap().1;
            
            // 删除风格选择，只保留开始游戏
            gameplay.state = GameplayState::LevelSelect;
        }
    }
}

pub fn run_win_menu_system(world: &mut World, context: &mut Context) {
    // Simple win menu - just press Enter to restart
    if context.keyboard.is_key_just_pressed(KeyCode::Return) {
        {
            let mut query = world.query::<&mut Gameplay>();
            let mut gameplay = query.iter().next().unwrap().1;
            gameplay.state = GameplayState::MainMenu; 
            gameplay.moves_count = 0;
        } // query 在这里被释放
        
        // Clear existing entities and reload level
        crate::map::clear_level(world);
    }
}

pub fn play_victory_sound(world: &mut World, context: &mut Context) {
    let mut query = world.query::<&mut AudioStore>();
    let audio_store = query.iter().next().unwrap().1;
    audio_store.play_sound(context, "vectory");
}

//新增关卡选择页面
pub struct LevelSelectState {
    pub selected: usize,
    pub total: usize,
}

impl Default for LevelSelectState {
    fn default() -> Self {
        Self { selected: 0, total: 3 } // 目前有2个关卡
    }
}

pub fn run_level_select_system(world: &mut World, context: &mut Context, level_state: &mut LevelSelectState, difficulty_state: &mut DifficultySelectState) {
    // 上下键选择关卡
    if context.keyboard.is_key_just_pressed(KeyCode::Up) {
        if level_state.selected == 0 {
            level_state.selected = level_state.total - 1;
        } else {
            level_state.selected -= 1;
        }
    }
    if context.keyboard.is_key_just_pressed(KeyCode::Down) {
        level_state.selected = (level_state.selected + 1) % level_state.total;
    }
    // 回车确认选择
    if context.keyboard.is_key_just_pressed(KeyCode::Return) {
        {
            let mut query = world.query::<&mut Gameplay>();
            let gameplay = query.iter().next().unwrap().1;
            gameplay.state = GameplayState::DifficultySelect;
        }
        // 保存选择的关卡号
        difficulty_state.selected_level = Some(level_state.selected + 1);
    }
}

pub fn run_return_menu_system(world: &mut World, context: &mut Context) {
    // 按任意键返回主菜单
    if context.keyboard.is_key_just_pressed(KeyCode::Return) {
        let mut query = world.query::<&mut Gameplay>();
        let gameplay = query.iter().next().unwrap().1;
        gameplay.state = GameplayState::MainMenu;
    }
}

//新增难度选择页面
pub struct DifficultySelectState {
    pub selected: usize,
    pub total: usize,
    pub selected_level: Option<usize>,  // 改为 Option<usize>
}


impl Default for DifficultySelectState {
    fn default() -> Self {
        Self { 
            selected: 0, 
            total: 2,
            selected_level: None,  // 不默认关卡号
        }
    }
}

pub fn run_difficulty_select_system(world: &mut World, context: &mut Context, state: &mut DifficultySelectState) {
    // 上下键选择难度
    if context.keyboard.is_key_just_pressed(KeyCode::Up) {
        if state.selected == 0 {
            state.selected = state.total - 1;
        } else {
            state.selected -= 1;
        }
    }
    if context.keyboard.is_key_just_pressed(KeyCode::Down) {
        state.selected = (state.selected + 1) % state.total;
    }
    // 回车确认选择
    if context.keyboard.is_key_just_pressed(KeyCode::Return) {
        // 检查是否已选择关卡
        if let Some(level) = state.selected_level {
            {
                let mut query = world.query::<&mut Gameplay>();
                let gameplay = query.iter().next().unwrap().1;
                gameplay.state = GameplayState::Playing;
                gameplay.difficulty = if state.selected == 0 { Difficulty::Easy } else { Difficulty::Hard };
                // 根据关卡和难度设置步数限制
                gameplay.max_moves = Gameplay::get_max_moves_for_level_and_difficulty(level, gameplay.difficulty);
            }
            crate::map::initialize_level(world, context, level);
        }
        // 如果没有选择关卡，可以在这里添加错误处理或提示
    }
}
pub fn run_failed_menu_system(world: &mut World, context: &mut Context) {
    // 按Enter键返回主菜单
    if context.keyboard.is_key_just_pressed(KeyCode::Return) {
        {
            let mut query = world.query::<&mut Gameplay>();
            let gameplay = query.iter().next().unwrap().1;
            gameplay.state = GameplayState::MainMenu;
            gameplay.moves_count = 0;
        }
        // 清除关卡
        crate::map::clear_level(world);
    }
}

pub fn play_failed_sound(world: &mut World, context: &mut Context) {
    let mut query = world.query::<&mut AudioStore>();
    let audio_store = query.iter().next().unwrap().1;
    audio_store.play_sound(context, "failed");
}
